package com.wy.common.util.tree;

import com.wy.entity.SysDept;
import org.apache.poi.ss.formula.functions.T;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

public class TreeCommon <T extends TreeFormat<T, P>, P extends Serializable> {

    public void  toTreeFormat(Collection<T> origin, Collection<T> target) {
        LinkedList<T> queue = new LinkedList<T>();
        Map<Object, T> cache = new HashMap<Object, T>();
        // 第一轮循环找到根节点. 初始化队列.
        for (T data : origin) {
            if (data.getTreeParentId() == null) {
                target.add(data);
            } else {
                queue.add(data);
            }
            cache.put(data.getTreeId(), data);
        }
        while (!queue.isEmpty()) {
            int queueSize = queue.size();
            for (int i = 0; i < queueSize; i++) {
                T data = queue.poll();
                T parent = cache.get(data.getTreeParentId());
                if (parent != null) {
                    parent.addChildren(data);
                } else {
                    queue.add(data);
                }
            }
            if (queue.size() == queueSize) {
                for (int i = 0; i < queueSize; i++) {
                    target.add(queue.poll());
                }
            }
        }
    }
}
